import * as Cesium from "cesium";

export default class TrackGridCell {


  constructor(viewer, position, size = 15.0) {
    this.viewer = viewer;
    this.position = position;
    // 立方体大小
    this.halfSize = size / 2;
    // 方向枚举
    // 将[经度,纬度,高度]数组转换为Cartesian3对象
    const cartesian = Cesium.Cartesian3.fromDegrees(
      position[0],
      position[1],
      position[2]
    );
    // 创建一个局部坐标系的变换矩阵，防止因地球曲率导致的变形
    const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
      cartesian,
      hpr
    );
    this.modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
      cartesian, // 平移
      orientation, // 旋转
      new Cesium.Cartesian3(1, 1, 1) // 缩放
    );
    // 启用场景抗锯齿
    this.viewer.scene.postProcessStages.fxaa.enabled = true;
    // 用于存储每个扩展层的顶点和颜色
    this.layers = [];
    // 初始化几何数据
    this.initGeometryData();
  }

  initGeometryData () {
    // 顶点坐标
    this.positions = new Float64Array([
      -this.halfSize,
      -this.halfSize,
      -this.halfSize, // 0
      this.halfSize,
      -this.halfSize,
      -this.halfSize, // 1
      this.halfSize,
      this.halfSize,
      -this.halfSize, // 2
      -this.halfSize,
      this.halfSize,
      -this.halfSize, // 3
      -this.halfSize,
      -this.halfSize,
      this.halfSize, // 4
      this.halfSize,
      -this.halfSize,
      this.halfSize, // 5
      this.halfSize,
      this.halfSize,
      this.halfSize, // 6
      -this.halfSize,
      this.halfSize,
      this.halfSize, // 7
    ]);

    // 索引
    this.indices = new Uint16Array([
      0,
      1,
      2,
      0,
      2,
      3, // 底面
      4,
      5,
      6,
      4,
      6,
      7, // 顶面
      0,
      1,
      5,
      0,
      5,
      4, // 前面
      1,
      2,
      6,
      1,
      6,
      5, // 右面
      2,
      3,
      7,
      2,
      7,
      6, // 后面
      3,
      0,
      4,
      3,
      4,
      7, // 左面
    ]);

    // 基础层(底部立方体)使用白色
    this.layers = [
      {
      }
    ];
  }

  /**
   * 绘制单个方格并添加到场景中
   * @param {Array} position [经度,纬度,高度] 方格的位置，默认使用当前实例的位置
   * @param {Cesium.Color|String} color 方格颜色，默认半透明白色
   * @param {Number} scale 方格缩放比例，默认为1
   * @return {Cesium.Primitive} 创建的方格primitive对象
   */
  drawGridCell (position, color, scale = 1.0) {
    // 使用传入参数或默认值
    const gridPosition = position || this.position;
    const gridColor = typeof color === 'string'
      ? Cesium.Color.fromCssColorString(color)
      : (color || new Cesium.Color(1.0, 1.0, 1.0, 0.2));

    // 如果提供了新位置，则创建新的变换矩阵
    let modelMatrix = this.modelMatrix;
    if (position) {
      // 创建新方格的Cartesian3位置
      const cartesian = Cesium.Cartesian3.fromDegrees(
        gridPosition[0],
        gridPosition[1],
        gridPosition[2]
      );

      // 创建局部坐标系变换矩阵
      const hpr = new Cesium.HeadingPitchRoll(0, 0, 0);
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        cartesian,
        hpr
      );
      modelMatrix = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
        cartesian,
        orientation,
        new Cesium.Cartesian3(scale, scale, scale)
      );
    }

    // 使用初始化时创建的几何数据    // 创建方格实例
    const primitive = new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.Geometry({
          attributes: {
            position: new Cesium.GeometryAttribute({
              componentDatatype: Cesium.ComponentDatatype.DOUBLE,
              componentsPerAttribute: 3,
              values: this.positions, // 使用初始化时创建的顶点数据
            }),
          },
          indices: this.indices, // 使用初始化时创建的索引数据
          primitiveType: Cesium.PrimitiveType.TRIANGLES,
          boundingSphere: Cesium.BoundingSphere.fromVertices(this.positions),
          vertexFormat: Cesium.VertexFormat.ALL,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(gridColor),
        },
        modelMatrix: modelMatrix, // 使用传入的或当前实例的模型矩阵
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: true,
        vertexFormat: Cesium.VertexFormat.ALL,
      }),
      asynchronous: false,
      releaseGeometryInstances: false,
      updatersPerAttribute: 1,
      renderState: {
        depthTest: {
          enabled: true,
        },
        depthMask: false,
        blending: Cesium.BlendingState.ALPHA_BLEND,
        framebuffer: {
          msaa: true,
        },
      },
    });

    // 将创建的方格添加到场景中
    this.viewer.scene.primitives.add(primitive);

    // 返回创建的方格对象，便于后续操作
    return primitive;
  }
}
